<template>
  <el-form :model="activity" :rules="rules" ref="activity" label-width="150px" class="demo-activity" enctype="multipart/form-data">
    <el-form-item label="活动名称" prop="activity_name">
      <el-input v-model="activity.activity_name" maxlength="30" show-word-limit name="activity_name"></el-input>
    </el-form-item>
    <el-form-item label="活动描述" prop="description">
      <el-input type="textarea" v-model="activity.description" :autosize="{ minRows: 10, maxRows: 10 }" resize="none" name="description"></el-input>
    </el-form-item>
    <el-form-item label="活动发起人" prop="initiator">
      <el-input v-model="activity.initiator" maxlength="20" show-word-limit name="initiator"></el-input>
    </el-form-item>
    <el-form-item label="活动地址" prop="address">
      <el-input v-model="activity.address" show-word-limit name="address"></el-input>
    </el-form-item>
    <el-form-item label="活动时间" prop="time">
      <el-date-picker
        v-model="activity.time"
        type="datetimerange"
        align="right"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :default-time="['08:00:00', '18:00:00']">
      </el-date-picker>
    </el-form-item>
    <el-form-item label="活动所需最小人数" prop="min_num">
      <el-col :span="3">
        <el-input-number v-model="activity.min_num" name="min_num" controls-position="right" :min="1" :max="99"></el-input-number>
      </el-col>
    </el-form-item>
    <el-form-item label="活动所需最大人数" prop="max_num">
      <el-col :span="3">
        <el-input-number v-model="activity.max_num" name="max_num" controls-position="right" :min="2" :max="99"></el-input-number>
      </el-col>
    </el-form-item>
    <el-form-item label="活动图片" prop="pictures">
      <el-upload
        action="#"
        list-type="picture-card"
        :auto-upload="false"
        multiple
        :limit="5"
        name="pictures"
        show-file-list
        :file-list="activity.pictures"
        :on-exceed="handlerExceed"
        :on-change="handleChange"
        accept="image/jpg, image/jpeg, image/png">
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过800kb，且最多只能上传5张</div>
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.url" alt=""
            >
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('activity')">立即发布</el-button>
      <el-button @click="resetForm('activity')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import { addActivity } from 'network/activity'
  export default {
    name: 'Add',
    data() {
      return {
        activity: {
          activity_name: '',
          description: '',
          initiator: '',
          address: '',
          time: '',
          min_num: 1,
          max_num: 2,
          pictures: []
        },
        activity_type: [],
        rules: {
          activity_name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
          ],
          description: [
            { required: true, message: '请输入活动描述', trigger: 'blur' }
          ],
          initiator: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
          ],
          address: [
            { required: true, message: '请输入活动地址', trigger: 'blur' }
          ],
          time: [
            { required: true, message: '请选择活动时间', trigger: 'change' }
          ],
          min_num: [
            { required: true, message: '请输入活动所需最小人数', trigger: 'blur' }
          ],
          max_num: [
            { required: true, message: '请输入活动所需最大人数', trigger: 'blur' }
          ]
        },
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false
      }
    },
    methods: {
      // 提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 数据合法，判断所需最小人数是否大于最大人数
            if (this.activity.min_num > this.activity.max_num) {
              return this.$message({
                type: 'error',
                message: '活动所需最小人数必须小于或等于最大人数！'
              })
            }
            // 数据合法，判断图片格式是否合法
            this.activity.pictures.some(item => {
              if (item.size > 819200) {
                return this.$message({
                  type: 'error',
                  message: '上传图片大小不能超过800kb，请更改后重试！'
                })
              }
            })
            // 获取时间
            let start_time = this.activity.time[0]
            let end_time = this.activity.time[1]
            let formData = new FormData()
            // pictures: (二进制)
            this.activity.pictures.forEach(item => {
              formData.append('pictures', item.raw)
            })
            console.log(formData.getAll('pictures'));
            formData.append('activity_name', this.activity.activity_name)
            formData.append('description', this.activity.description)
            formData.append('initiator', this.activity.initiator)
            formData.append('address', this.activity.address)
            formData.append('start_time', start_time)
            formData.append('end_time', end_time)
            formData.append('min_num', this.activity.min_num)
            formData.append('max_num', this.activity.max_num)
            // 调用添加海洋信息接口
            addActivity(formData).then(res => {
              if (res.status === 1) {
                console.log(res.message)
                return this.$message({
                  type: 'error',
                  message: res.message
                })
              }
              this.$message({
                type: 'success',
                message: '发布志愿活动成功！'
              })
              // 清空表单
              this.resetForm(formName)
            })
          } else {
            this.$message({
              type: 'error',
              message: '请输入完整且正确的信息！'
            })
            return false;
          }
        })
      },

      // 重置表单
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },

      // 删除文件
      handleRemove(file) {
        // 拿到当前文件的uid
        let uid = file.uid
        // 拿到 this.activity.pictures 里与 uid 相等的项，获得其下标 indexOf，将其移除 splice(下标, 1)
        let index = 0
        this.activity.pictures.forEach(item => {
          if (item.uid === uid) {
            index = this.activity.pictures.indexOf(item)
          }
        })
        this.activity.pictures.splice(index, 1)
      },

      // 预览图片
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },

      // 文件超出个数限制时的钩子
      handlerExceed() {
        this.$message({
          type: 'error',
          message: '最多上传5张图片！'
        })
      },

      // 添加图片时，拿到图片，保存在 activity.pictures 里
      handleChange(file) {
        this.activity.pictures.push(file)
      }
    }
  }
</script>

<style scoped>
  .el-form {
    width: 1200px;
  }
</style>